package com.isunny.mode.tactics.factory;

import com.isunny.mode.tactics.annotation.Eviction;
import com.isunny.mode.tactics.strategy.EvictionStrategy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 解析自定义注解工厂
 *
 * @author luom
 * @date 2022/2/25
 */
@Component
public class EvictionStrategyAnnotationPareFactory implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    private final Map<String, EvictionStrategy> evictionStrategyMap = new HashMap<>();

    public EvictionStrategy getEviction(String inputEviction) {
        Map<String, EvictionStrategy> evictionStrategyMaps = evictionStrategyMap();
        EvictionStrategy evictionStrategy = evictionStrategyMaps.get(inputEviction);
        if (evictionStrategy == null) {
            throw new UnsupportedOperationException("input eviction not found");
        }
        return evictionStrategy;
    }

    public Map<String, EvictionStrategy> evictionStrategyMap() {
        if (CollectionUtils.isEmpty(evictionStrategyMap)) {
            Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(Eviction.class);
            for (Object bean : beansWithAnnotation.values()) {
                if (bean instanceof EvictionStrategy) {
                    String evictionAnnotationValue = bean.getClass().getAnnotation(Eviction.class).value();
                    evictionStrategyMap.put(evictionAnnotationValue, (EvictionStrategy) bean);
                }
            }
        }
        return evictionStrategyMap;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
